#!usr/bin/env python3
# -*- coding: utf-8 -*-
from flask_httpauth import HTTPBasicAuth
from flask import g,jsonify
from . import api as apiBP
from .errors import unauthorized,forbidden
from ..models import User,AnonymousUser
from .apiconfig import is_config_ok

#http://www.cnblogs.com/vovlie/p/4182814.html

auth = HTTPBasicAuth()

# HTTPBasicAuth 是通过实现 verify_password 装饰器来验证的
@auth.verify_password
def verify_password(email_or_token,password):	
	if email_or_token=="" and is_config_ok('anonymous'): #如果允许匿名用户		
		g.current_user =AnonymousUser()
		return True
	if password=='': #不提供密码,表示通过令牌请求		
		g.current_user = User.verify_auth_token(email_or_token)
		g.token_used = True #是否是使用令牌验证
		return g.current_user is not None
	user = User.query.filter_by(email=email_or_token).first()
	if not user:
		return False
	g.current_user = user
	g.token_used = False
	return user.verify_password(password)

@auth.error_handler
def auth_error():
	return unauthorized("Invalid certificate")

#返回一个一小时内有效的令牌
def get_token_json(u):
	return {"token":u.make_id_token().decode('utf-8'),"expiration":3600}

#返回当前用户令牌
@apiBP.route("/token") 
def get_token():
	if g.current_user.is_anonymous or g.token_used:
		return unauthorized("Invalid certificate ")
	return jsonify(get_token_json(g.current_user)) 

#根据用户名回去令牌
@apiBP.route("/token/<string:username>")
def get_token_uname(username): 	
	u = User.query.filter_by(username=username).first()
	if not u:
		abort(404)
	return jsonify(get_token_json(u))

@apiBP.before_request
@auth.login_required
def before_request(): #在每次请求之前验证用户是否是已经登录是否是可信任的用户
	curUser = g.current_user	
	if not curUser.is_anonymous and not curUser.confirmed:
		return forbidden("未验证的账号")









